package com.example.microservice.common.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.microservice.dto.server.map.Coord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: caohuijie
 * @Date: 创建日期 2018/11/7
 * @Modified By:
 * @Description: 地图四至求取质心工具
 */
@Component
public class MapCenterPointUtil {

    /*//这里使用@value,取不到properties中的值，使用工具类来读取
    private final static ResourceBundle resourceBundle = ResourceBundle.getBundle("application");

    //转换坐标所需要的配置信息
    private  final static  String ak = resourceBundle.getString("geohey.ak");
    private  final static  String centroidurl = resourceBundle.getString("geohey.centroidurl");
    private  final static  String areaurl = resourceBundle.getString("geohey.areaurl");
    private  final static  String insr = resourceBundle.getString("geohey.insr");
    private  final static  String measuresr = resourceBundle.getString("geohey.measuresr");*/


    @Value("${geohey.ak}")
    private String ak;
    @Value("${geohey.measuresr}")
    private String measuresr;
    @Value("${geohey.centroidurl}")
    private String centroidurl;
    @Value("${geohey.areaurl}")
    private String areaurl;
    @Value("${geohey.insr}")
    private String insr;


    /**
     * 求取坐标的质心
     *
     * @param sPointValue
     * @return
     */
    public String getCenterPoint(String sPointValue) {

        /**
         * 1。组建参数
         */
        //初始化四维数据的各个值
        int arrFirst = 0;
        int arrSecend = 0;
        int arrThird = 0;
        int arrFour = 0;


        double maxKey = 0;
        int maxSecend = 0;
        int maxThird = 0;

        String[] splitCharFistArr = sPointValue.split("#");

        //处理参数
        arrFirst = splitCharFistArr.length;
        for (int i = 0; i < splitCharFistArr.length; i++) {
            String[] splitCharSecondArr = splitCharFistArr[i].split("\\$");
            if (arrFirst >= 2) {
                if (splitCharSecondArr.length > maxSecend) {
                    maxSecend = splitCharSecondArr.length;
                    arrSecend = maxSecend;
                }
            } else {
                arrSecend = splitCharSecondArr.length;
            }
            for (int k = 0; k < splitCharSecondArr.length; k++) {
                String[] splitCharThridArr = splitCharSecondArr[k].split("\\|");
                if (arrFirst >= 2) {
                    if (splitCharThridArr.length > maxThird) {
                        maxThird = splitCharThridArr.length;
                        arrThird = maxThird;
                    }
                } else {
                    arrThird = splitCharThridArr.length;
                }
                for (int j = 0; j < splitCharThridArr.length; j++) {
                    String[] splitCharFourArr = splitCharThridArr[j].split(",");
                    arrFour = splitCharFourArr.length;
                }
            }
        }


        String[][][][] str2 = new String[arrFirst][arrSecend][arrThird][arrFour];
        String[] p = sPointValue.split("#");
        for (int i = 0; i < p.length; i++) {
            String[] b = p[i].split("\\$");
            for (int k = 0; k < b.length; k++) {
                String[] c = b[k].split("\\|");
                for (int j = 0; j < c.length; j++) {
                    String[] d = c[j].split(",");
                    for (int z = 0; z < d.length; z++) {
                        str2[i][k][j][z] = d[z];
                    }
                }
            }
        }
        Map<Double, Object> mapArea = new HashMap<>();
        List<String[]> areaList = new ArrayList<>();
        String newStrMeasure = null;
        Double area = null;
        String newStrCentroid = null;
        String qualityPoint = null;
        mapArea.clear();
        areaList.clear();
        String[][][][] geom = str2;
        String jsonString = JSON.toJSONString(geom);
        jsonString = jsonString.replaceAll("\"", "");
        try {
            String areaUrl = areaurl + "ak=" + ak;
            RestTemplate restMeasure = new RestTemplate();
            MultiValueMap<String, Object> measureParam = new LinkedMultiValueMap<>();
            measureParam.add("inSR", insr);
            measureParam.add("measureSR", measuresr);
            measureParam.add("geometries", jsonString);
            String stringMeasure = restMeasure.postForObject(areaUrl, measureParam, String.class);
            newStrMeasure = new String(stringMeasure.getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        Map mapMeasure = JSON.parseObject(newStrMeasure);
        List list = (List) (mapMeasure.get("data"));

        for (int i = 0; i < geom.length; i++) {
            String[][][] str = geom[i];
            area = ((BigDecimal) list.get(i)).doubleValue();
            mapArea.put(area, str);
            if (area > maxKey) {
                maxKey = area;
            }
        }
        String[][][] maxPoint = (String[][][]) mapArea.get(maxKey);
        String centroidPoint = JSON.toJSONString(maxPoint);
        centroidPoint = centroidPoint.replaceAll("\"", "");
        if (centroidPoint != null && centroidPoint.length() > 0) {
            try {
                String centroidUrl = centroidurl + "ak=" + ak;
                RestTemplate restCentroid = new RestTemplate();
                MultiValueMap<String, Object> centroidParam = new LinkedMultiValueMap<>();
                centroidParam.add("geometries", centroidPoint);
                String stringCentroid = restCentroid.postForObject(centroidUrl, centroidParam, String.class);
                newStrCentroid = new String(stringCentroid.getBytes("iso-8859-1"), "utf-8");
                Map mapCentroid = JSON.parseObject(newStrCentroid);
                JSONArray centroidList = (JSONArray) (mapCentroid.get("data"));
                JSONArray qualityPointJson = (JSONArray) centroidList.get(0);
                qualityPoint = JSON.toJSONString(qualityPointJson);
                qualityPoint = qualityPoint.replace("[", "").replace("]", "");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return qualityPoint;
    }

    /**
     * 获取中心点x公里的愿的坐标
     *
     * @param coord    坐标
     * @param distacem 到中心的距离(正方形内切圆的半径）单位*米
     * @return 获取中心点x公里的愿的坐标
     */
    public static List<Coord> getCenterPointRan(Coord coord, double distacem) {
        //换算成千米
        double distace = distacem / 1000;
        List<Coord> coords = new ArrayList<>();
        double x = coord.getX();
        double y = coord.getY();
        //求取最大的几个坐标
        double dx = 2 * Math.asin(Math.sin(distace / (2 * 6371))
                / Math.cos(deg2rad(y)));
        dx = rad2deg(dx);

        double dy = distace / 6371;
        dy = rad2deg(dy);

        //leftTop
        coords.add(new Coord(x - dx, y + dy));
        //rightTop
        coords.add(new Coord(x + dx, y + dy));
        //leftBottom
        coords.add(new Coord(x - dx, y - dy));
        //rightBottom
        coords.add(new Coord(x + dx, y - dy));
        return coords;

    }

    //将角度转换为弧度
    private static double deg2rad(double degree) {
        return degree / 180 * Math.PI;
    }

    //将弧度转换为角度
    private static double rad2deg(double radian) {
        return radian * 180 / Math.PI;
    }


}
